<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<link rel="shortcut icon" type="image/x-icon" href="favicon.ico"/>
<title>DynamoRIO API: Sample Use Cases</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="navtree.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="resize.js"></script>
<script type="text/javascript" src="navtree.js"></script>
<script type="text/javascript">
  $(document).ready(initResizable);
</script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/search.js"></script>
<script type="text/javascript">
  $(document).ready(function() { searchBox.OnSelectItem(0); });
</script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
 <tbody>
 <tr style="height: 56px;">
  <td style="padding-left: 0.5em;">
   <div id="projectname">DynamoRIO API
   </div>
  </td>
   <td>        <div id="MSearchBox" class="MSearchBoxInactive">
        <span class="left">
          <img id="MSearchSelect" src="search/mag_sel.png"
               onmouseover="return searchBox.OnSearchSelectShow()"
               onmouseout="return searchBox.OnSearchSelectHide()"
               alt=""/>
          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)" 
               onblur="searchBox.OnSearchFieldFocus(false)" 
               onkeyup="searchBox.OnSearchFieldChange(event)"/>
          </span><span class="right">
            <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a>
          </span>
        </div>
</td>
 </tr>
 </tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.1.1 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "search",false,'Search');
</script>
</div><!-- top -->
<div id="side-nav" class="ui-resizable side-nav-resizable">
  <div id="nav-tree">
    <div id="nav-tree-contents">
    </div>
  </div>
  <div id="splitbar" style="-moz-user-select:none;" 
       class="ui-resizable-handle">
  </div>
</div>
<script type="text/javascript">
$(document).ready(function(){initNavTree('API_samples.html','');});
</script>
<div id="doc-content">
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
     onmouseover="return searchBox.OnSearchSelectShow()"
     onmouseout="return searchBox.OnSearchSelectHide()"
     onkeydown="return searchBox.OnSearchSelectKey(event)">
<a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(0)"><span class="SelectionMark">&#160;</span>All</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(1)"><span class="SelectionMark">&#160;</span>Data Structures</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(2)"><span class="SelectionMark">&#160;</span>Files</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(3)"><span class="SelectionMark">&#160;</span>Functions</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(4)"><span class="SelectionMark">&#160;</span>Variables</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(5)"><span class="SelectionMark">&#160;</span>Typedefs</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(6)"><span class="SelectionMark">&#160;</span>Enumerations</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(7)"><span class="SelectionMark">&#160;</span>Enumerator</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(8)"><span class="SelectionMark">&#160;</span>Macros</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(9)"><span class="SelectionMark">&#160;</span>Groups</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(10)"><span class="SelectionMark">&#160;</span>Pages</a></div>

<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0" 
        name="MSearchResults" id="MSearchResults">
</iframe>
</div>

<div class="header">
  <div class="headertitle">
<div class="title">Sample Use Cases </div>  </div>
</div><!--header-->
<div class="contents">
<div class="textblock"><p>We provide several examples in the <code>samples</code> directory of the release package to illustrate how the DynamoRIO API is used to build a DynamoRIO client.</p>
<p>There are also samples for the Dr. Memory Framework located in the <code>drmemory/drmf/samples</code> directory of the release package.</p>
<p>For larger examples of clients, see the provided <a class="el" href="page_tool.html">DynamoRIO-Based Tools</a>, which are larger and more polished end-user clients than these samples.</p>
<h1><a class="anchor" id="sample_list"></a>
List of Samples</h1>
<p>The sample <a href="../../samples/bbbuf.c">bbbuf.c</a> demonstrates how to use a TLS field for per-thread basic block profiling.</p>
<p>The sample <a href="../../samples/bbcount.c">bbcount.c</a> illustrates how to perform performant instrumentation for reporting the dynamic execution count of all basic blocks.</p>
<p>The sample <a href="../../samples/bbsize.c">bbsize.c</a> collects statistics on the sizes of all basic blocks in the target application.</p>
<p>The sample <a href="../../samples/cbr.c">cbr.c</a> collects conditional branch execution information and shows how to dynamically update or replace instrumented code after it executes.</p>
<p>The sample <a href="../../samples/cbrtrace.c">cbrtrace.c</a> collects conditional branch execution traces and writes them into files.</p>
<p>The sample <a href="../../samples/countcalls.c">countcalls.c</a> reports the dynamic execution count for direct calls, indirect calls, and returns in the target application. It illustrates how to perform performant inline increments and use per-thread data structures.</p>
<p>The sample <a href="../../samples/div.c">div.c</a> demonstrates profiling the types of values fed to a particular opcode.</p>
<p>The sample <a href="../../samples/empty.c">empty.c</a> is provided as an example client that does nothing.</p>
<p>The sample <a href="../../samples/inc2add.c">inc2add.c</a> performs a dynamic optimization: it converts the "inc" instruction to "add 1" without perturbing the target application's behavior.</p>
<p>The sample <a href="../../samples/inline.c">inline.c</a> performs an optimization that uses the custom trace API to inline entire callees into traces.</p>
<p>The sample <a href="../../samples/inscount.c">inscount.c</a> reports the dynamic count of the total number of instructions executed via inserting performant clean calls which are auto-inlined by DynamoRIO.</p>
<p>The sample <a href="../../samples/instrcall.c">instrcall.c</a> demonstrates how to instrument direct calls, indirect calls and returns.</p>
<p>The sample <a href="../../samples/memtrace.c">memtrace.c</a> is provided as an example client that illustrates how to create a private code cache and perform lean procedure calls.</p>
<p>The sample <a href="../../samples/modxfer.c">modxfer.c</a> reports the control flow transfers between modules.</p>
<p>The sample <a href="../../samples/modxfer.c">modxfer_app2lib.c</a> reports the control flow transfers between the application executable and other dynamic libraries and modules. It illustrates how to perform performant clean calls on different modules.</p>
<p>The sample <a href="../../samples/prefetch.c">prefetch.c</a> demonstrates modifying the dynamic code stream for compatibility between different processor types.</p>
<p>The sample <a href="../../samples/signal.c">signal.c</a> demonstrates how to use the signal event.</p>
<p>The sample <a href="../../samples/stl_test.c">stl_test.c</a> is provided as an example client that uses C++ STL containers.</p>
<p>The sample <a href="../../samples/syscall.c">syscall.c</a> displays how to use the system call events and API routines.</p>
<p>The sample <a href="../../samples/tracedump.c">tracedump.c</a> is provided as a standalone application that disassembles a trace dump in binary format produced by the -tracedump_binary option.</p>
<p>The sample <a href="../../samples/wrap.c">wrap.c</a> demonstrates how to use the drwrap extension (see <a class="el" href="page_drwrap.html">Function Wrapping and Replacing Extension</a>).</p>
<h1><a class="anchor" id="bt_examples"></a>
Discussion of Selected Samples</h1>
<h2><a class="anchor" id="sec_ex1"></a>
Instruction Counting</h2>
<p>We now illustrate how to use the above API to implement a simple instrumentation client for counting the number of executed call and return instructions in the input program. Full code for this example is in the file <a href="../../samples/countcalls.c">../../samples/countcalls.c</a>.</p>
<p>The client maintains set of three counters: num_direct_calls, num_indirect_calls, and num_returns to count three different types of instructions during execution. It keeps both thread-private and global versions of these counters. The client initializes everything by supplying the following dr_init routine:</p>
<div class="fragment"><div class="line">DR_EXPORT <span class="keywordtype">void</span></div>
<div class="line"><a class="code" href="dr__api_8h.html#a20a4dc9da7f6bb9121e30bb3570c6961">dr_init</a>(<a class="code" href="dr__defines_8h.html#a68540a70b4f8150a4fe6dcec91bf8825">client_id_t</a> <span class="keywordtype">id</span>)</div>
<div class="line">{</div>
<div class="line">  <span class="comment">/* register events */</span></div>
<div class="line">  <a class="code" href="dr__events_8h.html#a985537df683007e1392e8a3b095ef363">dr_register_exit_event</a>(event_exit);</div>
<div class="line">  <a class="code" href="dr__events_8h.html#a878920c40c76e2c18043f9db772a24c0">dr_register_thread_init_event</a>(event_thread_init);</div>
<div class="line">  <a class="code" href="dr__events_8h.html#a0b0c102bb9a99d67c3e62ea8b3790ff1">dr_register_thread_exit_event</a>(event_thread_exit);</div>
<div class="line">  <a class="code" href="dr__events_8h.html#a043a3588c4cf0c2d6838140fce530e72">dr_register_bb_event</a>(event_basic_block);</div>
<div class="line"></div>
<div class="line">  <span class="comment">/* make it easy to tell, by looking at log file, which client executed */</span></div>
<div class="line">  <a class="code" href="dr__tools_8h.html#a332a14861f12823994465e8c9b6a3015">dr_log</a>(NULL, <a class="code" href="dr__tools_8h.html#a7574ce4aa047de1f4a564c9b441e69dc">LOG_ALL</a>, 1, <span class="stringliteral">&quot;Client &#39;countcalls&#39; initializing\n&quot;</span>);</div>
<div class="line">}</div>
</div><!-- fragment --><p>The client provides an event_exit routine that displays the final values of the global counters as well as a thread_exit routine that shows the counter totals on a per-thread basis.</p>
<p>The client keeps track of each thread's instruction counts separately. To do this, it creates a data structure that will be separately allocated for each thread:</p>
<div class="fragment"><div class="line"><span class="keyword">typedef</span> <span class="keyword">struct </span>{</div>
<div class="line">  <span class="keywordtype">int</span> num_direct_calls;</div>
<div class="line">  <span class="keywordtype">int</span> num_indirect_calls;</div>
<div class="line">  <span class="keywordtype">int</span> num_returns;</div>
<div class="line">} per_thread_t;</div>
</div><!-- fragment --><p>Now the thread hooks are used to initialize the data structure and to display the thread-private totals :</p>
<div class="fragment"><div class="line"><span class="keyword">static</span> <span class="keywordtype">void</span> event_thread_init(<span class="keywordtype">void</span> *drcontext)</div>
<div class="line">{</div>
<div class="line">  <span class="comment">/* create an instance of our data structure for this thread */</span></div>
<div class="line">  per_thread *data = (per_thread *)</div>
<div class="line">    <a class="code" href="dr__tools_8h.html#a4274226adda06339e247e4a311abdd9b">dr_thread_alloc</a>(drcontext, <span class="keyword">sizeof</span>(per_thread));</div>
<div class="line">  <span class="comment">/* store it in the slot provided in the drcontext */</span></div>
<div class="line">  <a class="code" href="dr__tools_8h.html#a05b499c8a3115e9ceb4c45dbee660738">dr_set_tls_field</a>(drcontext, data);</div>
<div class="line">  data-&gt;num_direct_calls = 0;</div>
<div class="line">  data-&gt;num_indirect_calls = 0;</div>
<div class="line">  data-&gt;num_returns = 0;</div>
<div class="line">  <a class="code" href="dr__tools_8h.html#a332a14861f12823994465e8c9b6a3015">dr_log</a>(drcontext, <a class="code" href="dr__tools_8h.html#a7574ce4aa047de1f4a564c9b441e69dc">LOG_ALL</a>, 1, <span class="stringliteral">&quot;countcalls: set up for thread &quot;</span><a class="code" href="dr__defines_8h.html#a80e139e8f2d2dd7d5d4a92f8ad7c6f4d">TIDFMT</a><span class="stringliteral">&quot;\n&quot;</span>,</div>
<div class="line">         <a class="code" href="dr__tools_8h.html#a3980d703cc13379a6b57396a7901b1d1">dr_get_thread_id</a>(drcontext));</div>
<div class="line">}</div>
<div class="line"></div>
<div class="line"><span class="keyword">static</span> <span class="keywordtype">void</span> event_thread_exit(<span class="keywordtype">void</span> *drcontext)</div>
<div class="line">{</div>
<div class="line">  per_thread *data = (per_thread *) <a class="code" href="dr__tools_8h.html#a787aff5df1ded3de8a7ce9f3efef0594">dr_get_tls_field</a>(drcontext);</div>
<div class="line"></div>
<div class="line">  ... <span class="comment">// string formatting and displaying</span></div>
<div class="line"></div>
<div class="line">  <span class="comment">/* clean up memory */</span></div>
<div class="line">  <a class="code" href="dr__tools_8h.html#a3f1f3862009f52182e9ca1f943fa6f14">dr_thread_free</a>(drcontext, data, <span class="keyword">sizeof</span>(per_thread));</div>
<div class="line">}</div>
</div><!-- fragment --><p>The real work is done in the basic block hook. We simply look for the instructions we're interested in and insert an increment of the appropriate thread-local and global counters, remembering to save the flags, of course. This sample has separate paths for incrementing the thread private counts for shared vs. thread-private caches (see the -thread_private option) to illustrate the differences in targeting for them. Note that the shared path would work fine with private caches.</p>
<div class="fragment"><div class="line"><span class="keyword">static</span> <span class="keywordtype">void</span></div>
<div class="line">insert_counter_update(<span class="keywordtype">void</span> *drcontext, instrlist_t *bb, <a class="code" href="structinstr__t.html">instr_t</a> *where, <span class="keywordtype">int</span> offset)</div>
<div class="line">{</div>
<div class="line">  <span class="comment">/* Since the inc instruction clobbers 5 of the arithmetic eflags,</span></div>
<div class="line"><span class="comment">     we have to save them around the inc. We could be more efficient</span></div>
<div class="line"><span class="comment">     by not bothering to save the overflow flag and constructing our</span></div>
<div class="line"><span class="comment">     own sequence of instructions to save the other 5 flags (using</span></div>
<div class="line"><span class="comment">     lahf) or by doing a liveness analysis on the flags and saving</span></div>
<div class="line"><span class="comment">     only if live.</span></div>
<div class="line"><span class="comment">   */</span></div>
<div class="line">  <a class="code" href="dr__ir__utils_8h.html#a44636ca6809a9fb22cf817701de9ee09">dr_save_arith_flags</a>(drcontext, bb, where, SPILL_SLOT_1);</div>
<div class="line"></div>
<div class="line">  <span class="comment">/* Increment the global counter using the lock prefix to make it atomic</span></div>
<div class="line"><span class="comment">     across threads. It would be cheaper to aggregate the thread counters</span></div>
<div class="line"><span class="comment">     in the exit events, but this sample is intended to illustrate inserted</span></div>
<div class="line"><span class="comment">     instrumentation.</span></div>
<div class="line"><span class="comment">   */</span></div>
<div class="line">  <a class="code" href="dr__ir__utils_8h.html#a3b0b7e9e09a9a85ca1a707da3ded6f69">instrlist_meta_preinsert</a>(bb, where, <a class="code" href="dr__ir__macros_8h.html#a8104e895719c1f3a8558067b023cf9c5">LOCK</a>(<a class="code" href="dr__ir__macros_8h.html#a759b7342ed4080b9c12809d3b2e2718a">INSTR_CREATE_inc</a></div>
<div class="line">    (drcontext, <a class="code" href="dr__ir__macros_8h.html#a54b8bd667a8a940e94bfcc7842c958eb">OPND_CREATE_ABSMEM</a>(((byte *)&amp;global_count) + offset, <a class="code" href="dr__ir__opnd_8h.html#aaf8fd5f0e57d456151c951e0f3715fc4a0ccef0d75b3f473bf275388804c8b85c">OPSZ_4</a>))));</div>
<div class="line"></div>
<div class="line">  <span class="comment">/* Increment the thread private counter. */</span></div>
<div class="line">  <span class="keywordflow">if</span> (<a class="code" href="dr__tools_8h.html#a54934632c814904bd9e0ce9c83980466">dr_using_all_private_caches</a>()) {</div>
<div class="line">    per_thread_t *data = (per_thread_t *) <a class="code" href="dr__tools_8h.html#a787aff5df1ded3de8a7ce9f3efef0594">dr_get_tls_field</a>(drcontext);</div>
<div class="line">    <span class="comment">/* private caches - we can use an absolute address */</span></div>
<div class="line">    <a class="code" href="dr__ir__utils_8h.html#a3b0b7e9e09a9a85ca1a707da3ded6f69">instrlist_meta_preinsert</a>(bb, where, <a class="code" href="dr__ir__macros_8h.html#a759b7342ed4080b9c12809d3b2e2718a">INSTR_CREATE_inc</a>(drcontext,</div>
<div class="line">        <a class="code" href="dr__ir__macros_8h.html#a54b8bd667a8a940e94bfcc7842c958eb">OPND_CREATE_ABSMEM</a>(((byte *)&amp;data) + offset, <a class="code" href="dr__ir__opnd_8h.html#aaf8fd5f0e57d456151c951e0f3715fc4a0ccef0d75b3f473bf275388804c8b85c">OPSZ_4</a>)));</div>
<div class="line">  } <span class="keywordflow">else</span> {</div>
<div class="line">    <span class="comment">/* shared caches - we must indirect via thread local storage */</span></div>
<div class="line">    <span class="comment">/* We spill xbx to use a scratch register (we could do a liveness</span></div>
<div class="line"><span class="comment">       analysis to try and find a dead register to use). Note that xax</span></div>
<div class="line"><span class="comment">       is currently holding the saved eflags. */</span></div>
<div class="line">    <a class="code" href="dr__ir__utils_8h.html#af294ac021c84f5ec47230ee7df0e6c02">dr_save_reg</a>(drcontext, bb, where, REG_XBX, <a class="code" href="dr__ir__utils_8h.html#a89a6b714ff24d91d78589877047a29b9ae4cd78beccb2525acc61f2536ba1ea71">SPILL_SLOT_2</a>);</div>
<div class="line">    <a class="code" href="dr__ir__utils_8h.html#a3831354cc7402d68719d8055fb3e9931">dr_insert_read_tls_field</a>(drcontext, bb, where, REG_XBX);</div>
<div class="line">    <a class="code" href="dr__ir__utils_8h.html#a3b0b7e9e09a9a85ca1a707da3ded6f69">instrlist_meta_preinsert</a>(bb, where,</div>
<div class="line">        <a class="code" href="dr__ir__macros_8h.html#a759b7342ed4080b9c12809d3b2e2718a">INSTR_CREATE_inc</a>(drcontext, <a class="code" href="dr__ir__macros_8h.html#a026e7031693d6f0e4d53af107e0a1827">OPND_CREATE_MEM32</a>(REG_XBX, offset)));</div>
<div class="line">    <a class="code" href="dr__ir__utils_8h.html#a453bc3ecddb4298ffdc1c429f30881b8">dr_restore_reg</a>(drcontext, bb, where, REG_XBX, <a class="code" href="dr__ir__utils_8h.html#a89a6b714ff24d91d78589877047a29b9ae4cd78beccb2525acc61f2536ba1ea71">SPILL_SLOT_2</a>);</div>
<div class="line">  }</div>
<div class="line"></div>
<div class="line">  <span class="comment">/* restore flags */</span></div>
<div class="line">  <a class="code" href="dr__ir__utils_8h.html#a563b0de37a51cb2e84337deef30a57cf">dr_restore_arith_flags</a>(drcontext, bb, where, SPILL_SLOT_1);</div>
<div class="line">}</div>
<div class="line"></div>
<div class="line"><span class="keyword">static</span> <a class="code" href="dr__events_8h.html#a689518ac5d1ad136b13e03012702b209">dr_emit_flags_t</a></div>
<div class="line">event_basic_block(<span class="keywordtype">void</span> *drcontext, <span class="keywordtype">void</span> *tag, instrlist_t *bb,</div>
<div class="line">                  <span class="keywordtype">bool</span> for_trace, <span class="keywordtype">bool</span> translating)</div>
<div class="line">{</div>
<div class="line">  <a class="code" href="structinstr__t.html">instr_t</a> *instr, *next_instr;</div>
<div class="line"></div>
<div class="line">  ... <span class="comment">// some logging</span></div>
<div class="line"></div>
<div class="line">  <span class="keywordflow">for</span> (instr = <a class="code" href="dr__ir__instrlist_8h.html#ac9a47c1b7376ca06d8dcb4b3094e5a67">instrlist_first</a>(bb); instr != NULL; instr = next_instr) {</div>
<div class="line">    <span class="comment">/* grab next now so we don&#39;t go over instructions we insert */</span></div>
<div class="line">    next_instr = <a class="code" href="dr__ir__instr_8h.html#a9a11b5b0700f7601087e2fda87175040">instr_get_next</a>(instr);</div>
<div class="line"></div>
<div class="line">    <span class="comment">/* instrument calls and returns -- ignore far calls/rets */</span></div>
<div class="line">    <span class="keywordflow">if</span> (<a class="code" href="dr__ir__instr_8h.html#a5cb0fc26f65991c24002df14abb7e461">instr_is_call_direct</a>(instr)) {</div>
<div class="line">      insert_counter_update(drcontext, bb, instr,</div>
<div class="line">                            offsetof(per_thread_t, num_direct_calls));</div>
<div class="line">    } <span class="keywordflow">else</span> <span class="keywordflow">if</span> (<a class="code" href="dr__ir__instr_8h.html#a1fe1cc575e2870720ceee8ce134771f3">instr_is_call_indirect</a>(instr)) {</div>
<div class="line">      insert_counter_update(drcontext, bb, instr,</div>
<div class="line">                            offsetof(per_thread_t, num_indirect_calls));</div>
<div class="line">    } <span class="keywordflow">else</span> <span class="keywordflow">if</span> (<a class="code" href="dr__ir__instr_8h.html#ade184d50e1016f220a10f40a60a4f8ad">instr_is_return</a>(instr)) {</div>
<div class="line">      insert_counter_update(drcontext, bb, instr,</div>
<div class="line">                            offsetof(per_thread_t, num_returns));</div>
<div class="line">    }</div>
<div class="line">  }</div>
<div class="line"></div>
<div class="line">  ... <span class="comment">// some logging</span></div>
<div class="line"></div>
<div class="line">  <span class="keywordflow">return</span> <a class="code" href="dr__events_8h.html#a689518ac5d1ad136b13e03012702b209a7d25c4546544d1a8c0b77c69230772eb">DR_EMIT_DEFAULT</a>;</div>
<div class="line">}</div>
</div><!-- fragment --><dl class="section user"><dt>Building the Example</dt><dd></dd></dl>
<p>For general instructions on building a client, see <a class="el" href="using.html#sec_build">Building a Client</a>.</p>
<p>To build the <code>instrcalls.c</code> client using CMake, if <code>DYNAMORIO_HOME</code> is set to the base of the DynamoRIO release package:</p>
<div class="fragment"><div class="line">mkdir build</div>
<div class="line">cd build</div>
<div class="line">cmake -DDynamoRIO_DIR=$DYNAMORIO_HOME/cmake $DYNAMORIO_HOME/samples</div>
<div class="line">make instrcalls</div>
</div><!-- fragment --><p>To build 32-bit samples when using gcc with a default of 64-bit, use:</p>
<div class="fragment"><div class="line">mkdir build</div>
<div class="line">cd build</div>
<div class="line">CFLAGS=-m32 CXXFLAGS=-m32 cmake -DDynamoRIO_DIR=$DYNAMORIO_HOME/cmake $DYNAMORIO_HOME/samples</div>
<div class="line">make instrcalls</div>
</div><!-- fragment --><p>The result is a shared library instrcalls.dll or libinstrcalls.so. To invoke the client library, follow the instructions under <a class="el" href="page_deploy.html">Deployment</a>.</p>
<h2><a class="anchor" id="sec_ex2"></a>
Instruction Profiling</h2>
<p>The next example shows how to use the provided control flow instrumentation routines, which allow more sophisticated profiling than simply counting instructions. Full code for this example is in the file <a href="../../samples/instrcalls.c">../../samples/instrcalls.c</a>.</p>
<p>As in the previous example, the client is interested in direct and indirect calls and returns. The client wants to analyze the target address of each dynamic instance of a call or return. For our example, we simply dump the data in text format to a separate file for each thread. Since FILE cannot be exported from a DLL on Windows, we use the DynamoRIO-provided file_t type that hides the distinction between FILE and HANDLE to allow the same code to work on Linux and Windows. We make use of the thread initialization and exit routines to open and close the file. We store the file for a thread in the user slot in the drcontext.</p>
<div class="fragment"><div class="line"><span class="keyword">static</span> <span class="keywordtype">void</span> event_thread_init(<span class="keywordtype">void</span> *drcontext)</div>
<div class="line">{</div>
<div class="line">  <span class="comment">/* we&#39;re going to dump our data to a per-thread file */</span></div>
<div class="line">  file_t f;</div>
<div class="line">  <span class="keywordtype">char</span> logname[512];</div>
<div class="line"></div>
<div class="line">  ... <span class="comment">// filename generation</span></div>
<div class="line"></div>
<div class="line">  f = <a class="code" href="dr__tools_8h.html#ae3ae2190774a204af207602791a32cb6">dr_open_file</a>(fname, <span class="keyword">false</span><span class="comment">/*write*/</span>);</div>
<div class="line">  <a class="code" href="dr__tools_8h.html#a7c07630dffdfd92bc6ee63abf405768c">DR_ASSERT</a>(f != <a class="code" href="dr__defines_8h.html#a5f22fa59d1d8caa3fa4750147f559043">INVALID_FILE</a>);</div>
<div class="line"></div>
<div class="line">  <span class="comment">/* store it in the slot provided in the drcontext */</span></div>
<div class="line">  <a class="code" href="dr__tools_8h.html#a05b499c8a3115e9ceb4c45dbee660738">dr_set_tls_field</a>(drcontext, (<span class="keywordtype">void</span> *)f);</div>
<div class="line"></div>
<div class="line">  ... <span class="comment">// logging</span></div>
<div class="line">}</div>
<div class="line"></div>
<div class="line"><span class="keyword">static</span> <span class="keywordtype">void</span> event_thread_exit(<span class="keywordtype">void</span> *drcontext)</div>
<div class="line">{</div>
<div class="line">  file_t f = (file_t)(ptr_uint_t) <a class="code" href="dr__tools_8h.html#a787aff5df1ded3de8a7ce9f3efef0594">dr_get_tls_field</a>(drcontext);</div>
<div class="line">  <a class="code" href="dr__tools_8h.html#ac25b305e0be9f6c09f9761b14f3bbc74">dr_close_file</a>(f);</div>
<div class="line">}</div>
</div><!-- fragment --><p>The basic block hook inserts a call to a procedure for each type of instruction, using the API-provided dr_insert_call_instrumentation and dr_insert_mbr_instrumentation routines, which insert calls to procedures with a certain signature.</p>
<div class="fragment"><div class="line"><span class="keyword">static</span> <a class="code" href="dr__events_8h.html#a689518ac5d1ad136b13e03012702b209">dr_emit_flags_t</a></div>
<div class="line">event_basic_block(<span class="keywordtype">void</span> *drcontext, <span class="keywordtype">void</span> *tag, instrlist_t *bb,</div>
<div class="line">                  <span class="keywordtype">bool</span> for_trace, <span class="keywordtype">bool</span> translating)</div>
<div class="line">{</div>
<div class="line">  <a class="code" href="structinstr__t.html">instr_t</a> *instr, *next_instr;</div>
<div class="line"></div>
<div class="line">  ... <span class="comment">// logging</span></div>
<div class="line"></div>
<div class="line">  <span class="keywordflow">for</span> (instr = <a class="code" href="dr__ir__instrlist_8h.html#ac9a47c1b7376ca06d8dcb4b3094e5a67">instrlist_first</a>(bb); instr != NULL; instr = next_instr) {</div>
<div class="line">    next_instr = <a class="code" href="dr__ir__instr_8h.html#a9a11b5b0700f7601087e2fda87175040">instr_get_next</a>(instr);</div>
<div class="line">    <span class="keywordflow">if</span> (!<a class="code" href="dr__ir__instr_8h.html#afeaf6ea858ca81c8b9968e4be43749f6">instr_opcode_valid</a>(instr))</div>
<div class="line">        <span class="keywordflow">continue</span>;</div>
<div class="line">    <span class="comment">/* instrument calls and returns -- ignore far calls/rets */</span></div>
<div class="line">    <span class="keywordflow">if</span> (<a class="code" href="dr__ir__instr_8h.html#a5cb0fc26f65991c24002df14abb7e461">instr_is_call_direct</a>(instr)) {</div>
<div class="line">        <a class="code" href="dr__ir__utils_8h.html#a359744bc2776333fbf8f057931ca8eeb">dr_insert_call_instrumentation</a>(drcontext, bb, instr, (app_pc)at_call);</div>
<div class="line">    } <span class="keywordflow">else</span> <span class="keywordflow">if</span> (<a class="code" href="dr__ir__instr_8h.html#a1fe1cc575e2870720ceee8ce134771f3">instr_is_call_indirect</a>(instr)) {</div>
<div class="line">        <a class="code" href="dr__ir__utils_8h.html#a919e2106df67eaaa5bc6c49d736543b5">dr_insert_mbr_instrumentation</a>(drcontext, bb, instr, (app_pc)at_call_ind,</div>
<div class="line">                                      SPILL_SLOT_1);</div>
<div class="line">    } <span class="keywordflow">else</span> <span class="keywordflow">if</span> (<a class="code" href="dr__ir__instr_8h.html#ade184d50e1016f220a10f40a60a4f8ad">instr_is_return</a>(instr)) {</div>
<div class="line">        <a class="code" href="dr__ir__utils_8h.html#a919e2106df67eaaa5bc6c49d736543b5">dr_insert_mbr_instrumentation</a>(drcontext, bb, instr, (app_pc)at_return,</div>
<div class="line">                                      SPILL_SLOT_1);</div>
<div class="line">    }</div>
<div class="line">  }</div>
<div class="line">  <span class="keywordflow">return</span> <a class="code" href="dr__events_8h.html#a689518ac5d1ad136b13e03012702b209a7d25c4546544d1a8c0b77c69230772eb">DR_EMIT_DEFAULT</a>;</div>
<div class="line">}</div>
</div><!-- fragment --><p>These procedures look like this :</p>
<div class="fragment"><div class="line"><span class="keyword">static</span> <span class="keywordtype">void</span></div>
<div class="line">at_call(app_pc instr_addr, app_pc target_addr)</div>
<div class="line">{</div>
<div class="line">  file_t f = (file_t)(ptr_uint_t) <a class="code" href="dr__tools_8h.html#a787aff5df1ded3de8a7ce9f3efef0594">dr_get_tls_field</a>(<a class="code" href="dr__tools_8h.html#a13217cc252506b06184c7c72adedf26c">dr_get_current_drcontext</a>());</div>
<div class="line">  <a class="code" href="struct__dr__mcontext__t.html">dr_mcontext_t</a> mc;</div>
<div class="line">  <a class="code" href="dr__ir__utils_8h.html#a91ffde2808c16e07f323c34affa72209">dr_get_mcontext</a>(<a class="code" href="dr__tools_8h.html#a13217cc252506b06184c7c72adedf26c">dr_get_current_drcontext</a>(), &amp;mc, NULL);</div>
<div class="line">  <a class="code" href="dr__tools_8h.html#a1affb1a9f1c49c1959f1a01967a0a0d9">dr_fprintf</a>(f, <span class="stringliteral">&quot;CALL @ &quot;</span><a class="code" href="dr__defines_8h.html#a176e4c39a833f4d01f0ecd322c0f4343">PFX</a><span class="stringliteral">&quot; to &quot;</span><a class="code" href="dr__defines_8h.html#a176e4c39a833f4d01f0ecd322c0f4343">PFX</a><span class="stringliteral">&quot;, TOS is &quot;</span><a class="code" href="dr__defines_8h.html#a176e4c39a833f4d01f0ecd322c0f4343">PFX</a><span class="stringliteral">&quot;\n&quot;</span>,</div>
<div class="line">             instr_addr, target_addr, mc.<a class="code" href="struct__dr__mcontext__t.html#a4e1c58a65a0b7aa6c55b5f18a2e2fd34">xsp</a>);</div>
<div class="line">}</div>
<div class="line"></div>
<div class="line"><span class="keyword">static</span> <span class="keywordtype">void</span></div>
<div class="line">at_call_ind(app_pc instr_addr, app_pc target_addr)</div>
<div class="line">{</div>
<div class="line">  file_t f = (file_t)(ptr_uint_t) <a class="code" href="dr__tools_8h.html#a787aff5df1ded3de8a7ce9f3efef0594">dr_get_tls_field</a>(<a class="code" href="dr__tools_8h.html#a13217cc252506b06184c7c72adedf26c">dr_get_current_drcontext</a>());</div>
<div class="line">  <a class="code" href="dr__tools_8h.html#a1affb1a9f1c49c1959f1a01967a0a0d9">dr_fprintf</a>(f, <span class="stringliteral">&quot;CALL INDIRECT @ &quot;</span><a class="code" href="dr__defines_8h.html#a176e4c39a833f4d01f0ecd322c0f4343">PFX</a><span class="stringliteral">&quot; to &quot;</span><a class="code" href="dr__defines_8h.html#a176e4c39a833f4d01f0ecd322c0f4343">PFX</a><span class="stringliteral">&quot;\n&quot;</span>, instr_addr, target_addr);</div>
<div class="line">}</div>
<div class="line"></div>
<div class="line"><span class="keyword">static</span> <span class="keywordtype">void</span></div>
<div class="line">at_return(app_pc instr_addr, app_pc target_addr)</div>
<div class="line">{</div>
<div class="line">  file_t f = (file_t)(ptr_uint_t) <a class="code" href="dr__tools_8h.html#a787aff5df1ded3de8a7ce9f3efef0594">dr_get_tls_field</a>(<a class="code" href="dr__tools_8h.html#a13217cc252506b06184c7c72adedf26c">dr_get_current_drcontext</a>());</div>
<div class="line">  <a class="code" href="dr__tools_8h.html#a1affb1a9f1c49c1959f1a01967a0a0d9">dr_fprintf</a>(f, <span class="stringliteral">&quot;RETURN @ &quot;</span><a class="code" href="dr__defines_8h.html#a176e4c39a833f4d01f0ecd322c0f4343">PFX</a><span class="stringliteral">&quot; to &quot;</span><a class="code" href="dr__defines_8h.html#a176e4c39a833f4d01f0ecd322c0f4343">PFX</a><span class="stringliteral">&quot;\n&quot;</span>, instr_addr, target_addr);</div>
<div class="line">}</div>
</div><!-- fragment --><p>The address of the instruction and the address of its target are both provided. These routines could perform some sort of analysis based on these addresses. In our example we simply print out the data.</p>
<h2><a class="anchor" id="sec_ex3"></a>
Modifying Existing Instrumentation</h2>
<p>In this example, we show how to update or replace existing instrumentation after it executes. This ability is useful for clients performing adaptive optimization. In this example, however, we are interested in recording the direction of all conditional branches, but wish to remove the overhead of instrumentation once we've gathered that information. This code could form part of a dynamic CFG builder, where we want to observe the control-flow edges that execute at runtime, but remove the instrumentation after it executes.</p>
<p>While DynamoRIO supports direct fragment replacement, another method for re-instrumentation is to flush the fragment from the code cache and rebuild it in the basic block event callback. In other words, we take the following approach:</p>
<ol type="1">
<li>In the basic block event callback, insert separate instrumentation for the taken and fall-through edges.</li>
<li>When the basic block executes, note the direction taken and flush the fragment from the code cache.</li>
<li>When the basic block event triggers again, insert instrumentation only for the unseen edge. After both edges have triggered, remove all instrumentation for the cbr.</li>
</ol>
<p>We insert separate clean calls for the taken and fall-through cases. In each clean call, we record the observed direction and immediately flush the basic block using <a class="el" href="dr__tools_8h.html#abe87d17869a51a66d59eecf459d71cc0">dr_flush_region()</a>. Since that routine removes the calling block, we redirect execution to the target or fall-through address with <a class="el" href="dr__ir__utils_8h.html#a9f612cf9d0ca2025b23d30b6f5bb0231">dr_redirect_execution()</a>. The file <a href="../../samples/cbr.c">../../samples/cbr.c</a> contains the full code for this sample.</p>
<h2><a class="anchor" id="sec_ex4"></a>
Optimization</h2>
<p>For the next example we consider a client application for a simple optimization. The optimizer replaces every increment/decrement operation with a corresponding add/subtract operation if running on a Pentium 4, where the add/subtract is less expensive. For optimizations, we are less concerned with covering all the code that is executed; on the contrary, in order to amortize the optimization overhead, we only want to apply the optimization to hot code. Thus, we apply the optimization at the trace level rather than the basic block level. Full code for this example is in the file <a href="../../samples/inc2add.c">../../samples/inc2add.c</a>.</p>
<h2><a class="anchor" id="sec_ex5"></a>
Custom Tracing</h2>
<p>This example demonstrates the custom tracing interface. It changes DynamoRIO's tracing behavior to favor making traces that start at a call and end right after a return. It demonstrates the use of both custom trace API elements :</p>
<div class="fragment"><div class="line"><span class="keywordtype">int</span> query_end_trace(<span class="keywordtype">void</span> *drcontext, <span class="keywordtype">void</span> *trace_tag, <span class="keywordtype">void</span> *next_tag);</div>
<div class="line"><span class="keywordtype">bool</span> <a class="code" href="dr__tools_8h.html#a9e262e93823dbc5914eca34540afbc07">dr_mark_trace_head</a>(<span class="keywordtype">void</span> *drcontext, <span class="keywordtype">void</span> *tag);</div>
</div><!-- fragment --><p>Full code for this example is in the file <a href="../../samples/inline.c">../../samples/inline.c</a>.</p>
<h2><a class="anchor" id="sec_ex6"></a>
Use of Floating Point Operation in a Client</h2>
<p>Because saving the floating point state is very expensive, DynamoRIO seeks to do so on an as needed basis. If a client wishes to use floating point operations it must save and restore the application's floating point state around the usage. For an inserted clean call out of the code cache, this can be conveniently done using <a class="el" href="dr__ir__utils_8h.html#ae7b7bd1e750b8a24ebf401fb6a6d6d5e">dr_insert_clean_call()</a> and passing true for the save_fpstate parameter. It can also be done explicitly using these routines:</p>
<div class="fragment"><div class="line"><span class="keywordtype">void</span> <a class="code" href="dr__proc_8h.html#a4a11c9d5d127ce126562ad35b4d165dd">proc_save_fpstate</a>(byte *buf);</div>
<div class="line"><span class="keywordtype">void</span> <a class="code" href="dr__proc_8h.html#a23edceee5d1ae7c7d51a212432e6d644">proc_restore_fpstate</a>(byte *buf);</div>
</div><!-- fragment --><p>These routines must be used if floating point operations are performed in non-inserted-call locations, such as event callbacks. Note that there are restrictions on how these methods may be called: see the documentation in the header files for additional information. Note also that the floating point state must be saved around calls to our provided printing routines when they are used to print floats. However, it is not necessary to save and restore the floating point state around floating point operations if they are being used in the initialization or termination routines.</p>
<p>This example client counts the number of basic blocks processed and keeps statistics on their average size using floating point operations. Full code for this example is in the file <a href="../../samples/bbsize.c">../../samples/bbsize.c</a>.</p>
<h2><a class="anchor" id="sec_ex7"></a>
Use of Custom Client Statistics with the Windows GUI</h2>
<p>The new Windows GUI will display custom client statistics, if they are placed in shared memory with a certain name. The sample <a href="../../samples/stats.c">../../samples/stats.c</a> gives code for the protocol used in the form of a sample client that counts total instructions, floating-point instructions, and system calls.</p>
<p>Note that the stats.c example client and the Windows GUI must both be run within the same session in order for the statistics to be shared properly. They can be modified to use a "Global" prefix instead of "Local" for cross-session sharing, though this requires running with administrative privileges.</p>
<h2><a class="anchor" id="sec_ex8"></a>
Use of Standalone API</h2>
<p>The binary tracedump reader also functions as an example of <a class="el" href="page_standalone.html">IA-32/AMD64 Disassembly Library</a> : <a href="../../samples/tracedump.c">../../samples/tracedump.c</a>. </p>
</div></div><!-- contents -->
</div><!-- doc-content -->
<!-- start footer part -->
<div id="nav-path" class="navpath"><!-- id is needed for treeview function! -->
  <ul>
    <li class="footer" style="float:none;text-align:center"><img border=0 src="favicon.png"> &nbsp;  DynamoRIO API version 5.0.0 --- Wed Sep 10 2014 21:36:44 &nbsp; <img border=0 src="favicon.png">
</small></address>
<!--END !GENERATE_TREEVIEW-->
</body>
</html>
